package teshop.web;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import teshop.data.domain.Customer;
import teshop.service.CustomerService;
import teshop.utils.FileUploadingUtil;
import teshop.utils.to.CustomerTO;
import teshop.utils.to.Mapper;

@Component("newCustomer")
@Scope("request")
public class NewCustomer implements Serializable {

	/** Serial */
	private static final long serialVersionUID = -1911054473955466250L;

	@SuppressWarnings("unused")
	private CustomerService customerService;

	private CustomerTO customer = new CustomerTO();

	private UploadedFile photo;

	@Autowired
	public NewCustomer(CustomerService customerService) {
		this.customerService = customerService;
	}

	public CustomerTO getCustomer() {
		return customer;
	}

	public void setCustomer(CustomerTO customer) {
		this.customer = customer;
	}

	public String save() {
		Customer customer = new Customer();
		Mapper.mapCustomerTO2Entity(this.customer, customer);
		customerService.addCustomer(customer);

		uploadImage();
		printMessage();

		return null;
	}

	/**
	 * Uploading an image
	 */
	private void uploadImage() {
		try {
			FileUploadingUtil upload = 
				new FileUploadingUtil(FileUploadingUtil.IMAGE_DIR_PATH, "82716348");
			upload.parseExtension(photo.getName());
			upload.uploadImage(photo.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void printMessage() {
		FacesMessage facesMessage = new FacesMessage(
				FacesMessage.SEVERITY_INFO, "Everything is ", "OK");
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);

		customer = new CustomerTO();
	}

	public void setPhoto(UploadedFile photo) {
		this.photo = photo;
	}

	public UploadedFile getPhoto() {
		return photo;
	}

}
